package com.lzclass.filter;

import com.lzclass.util.JwtUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebFilter(value = "/user/*",dispatcherTypes={DispatcherType.REQUEST,DispatcherType.ASYNC})
public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("用户验证拦截");

        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;

        HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse;

        String token = httpServletRequest.getParameter("token");

        if(token==null){
            httpServletResponse.getWriter().write("MissToken");
        }else{
            Map<String, Object> map = JwtUtil.checkToken(token);

            if(map.get("state").equals("OK")){
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                httpServletResponse.getWriter().write("CheckError");
            }
        }

    }

    @Override
    public void destroy() {

    }
}
